package engine.systems.spatial.boundsBind
{
	import engine.classes.enumerations.SystemPriority;
	import engine.systems.motion.motion.Motion;
	import engine.systems.spatial.spatial.Spatial;
	import engine.systems.update.GameSystem;
	
	import flash.geom.Rectangle;
	
	public class BoundsBindSystem extends GameSystem
	{
		public function BoundsBindSystem()
		{
			super(BoundsBindNode, updateNode);
			
			this.priority = SystemPriority.COLLISION;
		}
		
		private function updateNode(node:BoundsBindNode, time:Number):void
		{
			var spatial:Spatial 	= node.spatial;
			var motion:Motion 		= node.motion;
			var bounds:BoundsBind 	= node.bounds;
			var rect:Rectangle 		= bounds.rect;
			
			var left:Number 	= 0;
			var right:Number 	= 0;
			var top:Number 		= 0;
			var bottom:Number 	= 0;
			
			if(node.edge)
			{
				left 	= node.edge.scaledLeft;
				right 	= node.edge.scaledRight;
				top 	= node.edge.scaledTop;
				bottom 	= node.edge.scaledBottom;
			}
			
			if(bounds.useLeft)
			{
				if(spatial.x - left < rect.left)
				{
					spatial.x = rect.left + left;
					if(motion) motion.velocityX *= -bounds.dampening;
					
					bounds.onLeft.dispatch(node.entity);
				}
			}
			
			if(bounds.useRight)
			{
				if(spatial.x + right > rect.right)
				{
					spatial.x = rect.right - right;
					if(motion) motion.velocityX *= -bounds.dampening;
					
					bounds.onRight.dispatch(node.entity);
				}
			}
			
			if(bounds.useTop)
			{
				if(spatial.y + top < rect.top)
				{
					spatial.y = rect.top - top;
					if(motion) motion.velocityY *= -bounds.dampening;
					
					bounds.onTop.dispatch(node.entity);
				}
			}
			
			if(bounds.useBottom)
			{
				if(spatial.y + bottom > rect.bottom)
				{
					spatial.y = rect.bottom - bottom;
					if(motion) motion.velocityY *= -bounds.dampening;
					
					bounds.onBottom.dispatch(node.entity);
				}
			}
		}
	}
}